package com.atomdayl.domain.therecipe.network;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.SystemClock;

import com.atomdayl.domain.therecipe.utils.LogUtils;
import com.atomdayl.domain.therecipe.utils.PreferencesUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.SocketTimeoutException;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.protocol.HTTP;


/**
 * Created by David on 2016/6/4.
 */
public class NetworkManager {

    public static final String SERVER_IP = "http://10.0.2.2";
    //我不清楚你这边端口号是多少
    public static final String SERVER_PORT = ":8080";

    public static final String URL = "/recipe/shiPu/";

    private static NetworkManager mInstance;
    public static boolean stop = false;
    final static String TAG = "net";
    private static long requestLifetime;

    private NetworkManager() {
    }

    public static NetworkManager getInstance() {
        if(mInstance == null) {
            synchronized (NetworkManager.class) {
                if(mInstance == null) {
                    mInstance = new NetworkManager();
                }
            }
        }

        return mInstance;
    }
    public String doPost(Context context , String reqUrl, String postParameter) {
        LogUtils.i(TAG, "url : " + reqUrl + ", param : " + postParameter);
        DefaultHttpClient httpClient = null;
        long startTime = SystemClock.elapsedRealtime();
        if (reqUrl.startsWith("https")) {
            BasicHttpParams params = new BasicHttpParams();
            SchemeRegistry sr = new SchemeRegistry();
            sr.register(new Scheme("https", new EasySSLSocketFactory(), 443));
            //某些手机必须注册http，否则会报错，注意，有问题联系hwq或者shx
            sr.register(new Scheme("http", PlainSocketFactory.getSocketFactory(),80));
            ClientConnectionManager cm = new ThreadSafeClientConnManager(params, sr);
            httpClient = new DefaultHttpClient(cm, params);
        } else {
            httpClient = new DefaultHttpClient();

        }

        // 连接超时
        httpClient.getParams().setParameter(
                CoreConnectionPNames.CONNECTION_TIMEOUT, 30000);
        // 请求超时
        httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT,
                60000);
        if (stop) {
            LogUtils.i("net", "dopost this first");
            stop = false;
            return "stop";
        }
        HttpPost httppost = new HttpPost(reqUrl);
        int ab = PreferencesUtils.getInt(context, PreferencesUtils.CLIENT_LOGIN, PreferencesUtils.AB_FLAG, 0);
        httppost.addHeader("ab", "" + ab);
        LogUtils.i("net", "header:[ab=" + ab + "]");
        httppost.addHeader("Content-Type", "application/json");
        httppost.addHeader("charset", HTTP.UTF_8);

        LogUtils.i("requestUrl", "dopost this first");
        InputStream content = null;
        String returnConnection = null;
        if (stop) {
            stop = false;
            return "stop";
        }
        try {
            // UrlEncodedFormEntity p_entity = new UrlEncodedFormEntity(pairs,
            // "utf-8");
            if (stop) {
                stop = false;
                return "stop";
            }
            /** 将POST数据放入http请求 */
            httppost.setEntity(new StringEntity(postParameter, HTTP.UTF_8));
            // httppost.setEntity(new
            // StringEntity(URLEncoder.encode(postParameter, "UTF-8")));

            /** 发出实际的HTTP POST请求 */
            if (stop) {
                stop = false;
                return "stop";
            }
            HttpResponse response = httpClient.execute(httppost);
            requestLifetime = SystemClock.elapsedRealtime() - startTime;
            if (stop) {
                stop = false;
                return "stop";
            }
            if (200 == response.getStatusLine().getStatusCode()) {
                HttpEntity entity = response.getEntity();
                content = entity.getContent();
                if (stop) {
                    stop = false;
                    return "stop";
                }
                returnConnection = convertStreamToString(content);

            } else {
                return "网络请求失败，请稍后再试";
            }

        } catch (ConnectTimeoutException ex) {
            ex.printStackTrace();
            return "网络连接超时，请稍后再试";
        } catch (SocketTimeoutException ex) {
            ex.printStackTrace();
            return "系统响应超时，请稍后查看结果";
        } catch (Exception ex) {
            ex.printStackTrace();
            return "您的网络异常，请检查网络后再试";
        } finally {
            try {
                if (content != null) {
                    content.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
                return null;
            }
        }
        if (stop) {
            stop = false;
            return "stop";
        }
        httpClient.getConnectionManager().shutdown();
        LogUtils.d(TAG, returnConnection);
        return returnConnection;
    }

    public String doGet(Context context, String reqUrl) {
        LogUtils.i(TAG, "url : " + reqUrl);
        DefaultHttpClient httpClient = new DefaultHttpClient();
        if (reqUrl.startsWith("https")) {
            BasicHttpParams params = new BasicHttpParams();
            SchemeRegistry sr = new SchemeRegistry();
            sr.register(new Scheme("https", new EasySSLSocketFactory(), 443));
            //某些手机必须注册http，否则会报错，注意，有问题联系hwq或者shx
            sr.register(new Scheme("http",PlainSocketFactory.getSocketFactory(),80));
            ClientConnectionManager cm = new ThreadSafeClientConnManager(params, sr);
            httpClient = new DefaultHttpClient(cm, params);
        } else {
            httpClient = new DefaultHttpClient();
        }

        // 连接超时
        httpClient.getParams().setParameter(
                CoreConnectionPNames.CONNECTION_TIMEOUT, 30000);
        // 请求超时
        httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT,
                60000);
        if (stop) {
            stop = false;
            return "stop";
        }
        HttpGet httpGet = new HttpGet(reqUrl);
        int ab = PreferencesUtils.getInt(context, PreferencesUtils.CLIENT_LOGIN, PreferencesUtils.AB_FLAG, 0);
        httpGet.addHeader("ab", "" + ab);
        LogUtils.i("net", "header:[ab=" + ab + "]");
        InputStream content = null;
        String returnConnection = null;
        if (stop) {
            stop = false;
            return "stop";
        }
        try {
            if (stop) {
                stop = false;
                return "stop";
            }

            /** 发出实际的HTTP POST请求 */
            if (stop) {
                stop = false;
                return "stop";
            }
            HttpResponse response = httpClient.execute(httpGet);
            if (stop) {
                stop = false;
                return "stop";
            }
            if (200 == response.getStatusLine().getStatusCode()) {
                HttpEntity entity = response.getEntity();
                content = entity.getContent();
                if (stop) {
                    stop = false;
                    return "stop";
                }
                returnConnection = convertStreamToString(content);

            } else {
                return "网络请求失败，请稍后再试";
            }

        } catch (ConnectTimeoutException ex) {
            ex.printStackTrace();
            return "网络连接超时，请稍后再试";
        } catch (SocketTimeoutException ex) {
            ex.printStackTrace();
            return "系统响应超时，请稍后查看结果";
        } catch (Exception ex) {
            ex.printStackTrace();
            return "您的网络异常，请检查网络后再试";
        } finally {
            try {
                if (content != null) {
                    content.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
                return null;
            }
        }
        if (stop) {
            stop = false;
            return "stop";
        }
        httpClient.getConnectionManager().shutdown();
        LogUtils.d(TAG, returnConnection);
        return returnConnection;
    }

    public static String convertStreamToString(InputStream is) {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();

        String line = null;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }

    public static boolean checkNetWork(Context context) {
        // 判断网络是否可用，如果不可用，给出提示
        boolean isAvailable = netWorkIsAvailable(context);
        return isAvailable;
    }

    public static boolean netWorkIsAvailable(Context context) {
        ConnectivityManager connectivityManager = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo();
        if (activeNetInfo != null) {
            if (activeNetInfo.isAvailable()) {
                return true;
            } else {
                return false;
            }
        }
        return false;
    }

    private static void openDialog(final Context context) {
        final AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setTitle("没有可用的网络");
        builder.setMessage("请开启GPRS或WIFI网络连接");
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int whichButton) {
                Intent intent = new Intent("android.settings.WIRELESS_SETTINGS");
                context.startActivity(intent);

            }
        }).setNeutralButton("取消", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int whichButton) {
                dialog.cancel();
            }
        }).create().show();
    }

    public static String doNameValueParePost(String reqUrl, List<NameValuePair> paramList) {
        DefaultHttpClient httpClient = null;
        if (reqUrl.startsWith("https")) {
            BasicHttpParams params = new BasicHttpParams();
            SchemeRegistry sr = new SchemeRegistry();
            sr.register(new Scheme("https", new EasySSLSocketFactory(), 443));
            ClientConnectionManager cm = new ThreadSafeClientConnManager(params, sr);
            httpClient = new DefaultHttpClient(cm, params);
        } else {
            httpClient = new DefaultHttpClient();

        }

        // 连接超时
        httpClient.getParams().setParameter(
                CoreConnectionPNames.CONNECTION_TIMEOUT, 30000);
        // 请求超时
        httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT,
                60000);
        if (stop) {
            LogUtils.i("net", "dopost this first");
            stop = false;
            return "stop";
        }
        HttpPost httppost = new HttpPost(reqUrl);
        //int ab = PreferencesUtil.getInt(Preferences.CLIENT_LOGIN, Preferences.AB_FLAG, 0);
        //httppost.addHeader("ab", "" + ab);
        //LogUtils.i("net", "header:[ab=" + ab + "]");
        httppost.addHeader("Content-Type", "application/x-www-form-urlencoded");
        // httppost.addHeader("charset", HTTP.UTF_8);

        LogUtils.i("requestUrl", "dopost this first");
        InputStream content = null;
        String returnConnection = null;
        if (stop) {
            stop = false;
            return "stop";
        }
        try {
            // UrlEncodedFormEntity p_entity = new UrlEncodedFormEntity(pairs,
            // "utf-8");
            if (stop) {
                stop = false;
                return "stop";
            }
            /** 将POST数据放入http请求 */
            httppost.setEntity(new UrlEncodedFormEntity(paramList,HTTP.UTF_8));
            // httppost.setEntity(new
            // StringEntity(URLEncoder.encode(postParameter, "UTF-8")));

            /** 发出实际的HTTP POST请求 */
            if (stop) {
                stop = false;
                return "stop";
            }
            HttpResponse response = httpClient.execute(httppost);
            if (stop) {
                stop = false;
                return "stop";
            }
            if (200 == response.getStatusLine().getStatusCode()) {
                HttpEntity entity = response.getEntity();
                content = entity.getContent();
                if (stop) {
                    stop = false;
                    return "stop";
                }
                returnConnection = convertStreamToString(content);

            } else {
                return "网络请求失败，请稍后再试";
            }

        } catch (ConnectTimeoutException ex) {
            ex.printStackTrace();
            return "网络连接超时，请稍后再试";
        } catch (SocketTimeoutException ex) {
            ex.printStackTrace();
            return "系统响应超时，请稍后查看结果";
        } catch (Exception ex) {
            ex.printStackTrace();
            return "您的网络异常，请检查网络后再试";
        } finally {
            try {
                if (content != null) {
                    content.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
                return null;
            }
        }
        if (stop) {
            stop = false;
            return "stop";
        }
        httpClient.getConnectionManager().shutdown();
        LogUtils.d(TAG, returnConnection);
        return returnConnection;
    }
}
